/**
 * Created by samli on 2017/2/16.
 */
import api from '../api/index';
import { Toast }  from 'mint-ui';

var IMserver = function () {
	this.conn = null;
	this.messageList = [];
	this.myHeadimgurl = '';
	this.nickname = '';
	this.groups_groupid = '';
}
IMserver.prototype.initGroupChat = function (gid) {
	var that = this;
	this.nickname = localStorage.nickname;
	this.myHeadimgurl = localStorage.headimgurl;
	this.groups_groupid = gid;
	if(typeof this.chatStatus === 'undefined') {
		this.chatStatus = 'padding';
	}
	this.getNowFormatDate = function (timestamp) {
		if (typeof timestamp === 'undefined') {
			var date = new Date();
		} else {
			var date = new Date(timestamp*1000);
		}
		var seperator1 = "-";
		var seperator2 = ":";
		var month = date.getMonth() + 1;
		var strDate = date.getDate();
		var strHour = date.getHours();
		var strMinute = date.getMinutes();
		var strSecond = date.getSeconds();
		if (month >= 1 && month <= 9) {
			month = "0" + month;
		}
		if (strDate >= 0 && strDate <= 9) {
			strDate = "0" + strDate;
		}
		if (strHour >= 0 && strHour <= 9) {
			strHour = "0" + strHour;
		}
		if (strMinute >= 0 && strMinute <= 9) {
			strMinute = "0" + strMinute;
		}
		if (strSecond >= 0 && strSecond <= 9) {
			strSecond = "0" + strSecond;
		}
		var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
				+ " " + strHour + seperator2 + strMinute
				+ seperator2 + strSecond;
		return currentdate;
	},
	this.conn.listen({
		onOpened: function(message) { //连接成功回调
			// 如果isAutoLogin设置为false，那么必须手动设置上线，否则无法收消息
			// 手动上线指的是调用conn.setPresence(); 如果conn初始化时已将isAutoLogin设置为true
			// 则无需调用conn.setPresence();
			console.log(message);
			that.chatStatus = 'ready';
		},
		onClosed: function(message) {
			console.log(message);
			// console.log(message);
		}, //连接关闭回调
		onTextMessage: function(message) {
			if(message.type == 'groupchat') {
				if(message.to!=that.groups_groupid)return;
				var uid = message.from;
				if(message.from == '官方消息')return;
				if(message.from == '师门官方'){
					var msgJson = {
						data:message.data,
						type:message.ext.type,
						user:message.ext.user_nick_name,
						SendTime:that.getNowFormatDate(message.ext.sendtime),
						isSend : true
					};
					localStorage['chatList'+gid] += 'yh2016*' + JSON.stringify(msgJson);
					return that.messageList.push(msgJson);
				}
				if(message.ext.headimgurl){
					var msgJson = {
						data:message.data,
						type:message.ext.type || 'message',
						user:message.ext.nickname,
						avator:message.ext.headimgurl,
						SendTime:that.getNowFormatDate(message.ext.sendtime),
						isSend : false
					};
					that.messageList.push(msgJson);
					return localStorage['chatList'+gid] += 'yh2016*' + JSON.stringify(msgJson);
				}else{
					api.getUserInfo({
						userId : uid
					}).then(function (response) {
						var data = response.data.data;
						var msgJson = {
							data:message.data,
							user:data.name,
							type:'message',
							avator:data.headimgurl,
							SendTime:that.getNowFormatDate(message.ext.sendtime),
							isSend : false
						};
						that.messageList.push(msgJson);
						return localStorage['chatList'+gid] += 'yh2016*' + JSON.stringify(msgJson);
					});
				}
			}
		}, //收到文本消息
		onEmojiMessage: function(message) {
			console.log(message);
		}, //收到表情消息
		onPictureMessage: function(message) {
			console.log(message);
		}, //收到图片消息
		onCmdMessage: function(message) {
			console.log(message);
		}, //收到命令消息
		onAudioMessage: function(message) {
			console.log(message);
		}, //收到音频消息
		onLocationMessage: function(message) {
			console.log(message);
		}, //收到位置消息
		onFileMessage: function(message) {
			console.log(message);
		}, //收到文件消息
		onVideoMessage: function(message) {
			var node = document.getElementById('privateVideo');
			var option = {
				url: message.url,
				headers: {
					'Accept': 'audio/mp4'
				},
				onFileDownloadComplete: function(response) {
					var objectURL = WebIM.utils.parseDownloadResponse.call(conn, response);
					node.src = objectURL;
				},
				onFileDownloadError: function() {
					console.log('File down load error.')
				}
			};
			WebIM.utils.download.call(conn, option);
		}, //收到视频消息
		onPresence: function(message) {
			console.log(message);
		}, //收到联系人订阅请求、处理群组、聊天室被踢解散等消息
		onRoster: function(message) {
			console.log(message);
		}, //处理好友申请
		onInviteMessage: function(message) {
			console.log(message);
		}, //处理群组邀请
		onOnline: function(message) {
			that.chatStatus = "ready";
			Toast('重连成功');
		}, //本机网络连接成功
		onOffline: function(message) {
			that.chatStatus = 'close';
			Toast('你已退出群聊');
		}, //本机网络掉线
		onError: function(message) {
			that.chatStatus = 'close';
			Toast('您的网路有误，稍后再试');
		}, //失败回调
		onBlacklistUpdate: function(list) { //黑名单变动
			// 查询黑名单，将好友拉黑，将好友从黑名单移除都会回调这个函数，list则是黑名单现有的所有好友信息
			console.log(list);
		}
	});
	var options = {
		apiUrl: WebIM.config.apiURL,
		user: localStorage.name,
		pwd: localStorage.password,
		appKey: WebIM.config.appkey
	};
	this.conn.open(options);
}
IMserver.prototype.connect = function (https,url,isAutoLoginBoo,isMultiLoginSessions) {
	this.conn = new WebIM.connection({
		https: https,
		url: url,
		isAutoLogin: isAutoLoginBoo,
		isMultiLoginSessions: isMultiLoginSessions
	});
}
IMserver.prototype.sendMessage = function (txt,okFn,errorFn) {
	const timestamp = Date.parse(new Date())/1000;
	var id = this.conn.getUniqueId();
	var msg = new WebIM.message('txt', id);
	var _imS = this;
	var gid = this.groups_groupid;
	var msgJson = {
		data:txt,
		user:'我',
		SendTime: _imS.getNowFormatDate(timestamp),
		avator:_imS.myHeadimgurl,
		isSend : true,
		type:'message'
	};
	_imS.messageList.push(msgJson);
	okFn&&okFn();
	var option = {
		msg: txt,
		to: gid,
		roomType: false,
		ext :{
			'nickname':this.nickname,
			'headimgurl' : this.myHeadimgurl,
			'sendtime' : timestamp
		},
		chatType: 'chatRoom',
		success: function () {
			localStorage['chatList'+gid] += 'yh2016*' + JSON.stringify(msgJson);
			console.log('send room text success');
		},
		fail: function () {
			errorFn&&errorFn();
			console.log('failed');
		}
	};
	msg.set(option);
	msg.setGroup('groupchat');
	this.conn.send(msg.body);
}
module.exports = IMserver;
